# -*- coding: utf-8 -*-
# filename: handle.py

import web
import pymysql
import json
from mysql_login_info import MYSQL_HOST, MYSQL_ACCOUNT, MYSQL_PASSWORD, MYSQL_DATABASE, MYSQL_PORT


def getHtmlPage():
    with open("index.html", "rb") as fs:
        HTML_PAGE = fs.read()
    return HTML_PAGE

DBParaTuple = (('temp_tbl', 'tp', 'tp_time'),
               ('humi_tbl', 'hm', 'hm_time'),
               ('pm2_5_tbl', 'pm', 'pm_time'),
               # ('form_tbl', 'fm', 'fm_time'),
               # ('tolu_tbl', 'tl', 'tl_time'),
               ('co2_tbl', 'cd', 'cd_time'),
)
EnvDataDict = {'tp':0.0, 'tp_time':'2017-12-07 00:00:00',
               'hm':0.0, 'hm_time':'2017-12-07 00:00:00',
               'pm':0.0, 'pm_time':'2017-12-07 00:00:00',
               # 'fm':0.0, 'fm_time':'2017-12-07 00:00:00',
               # 'tl':0.0, 'tl_time':'2017-12-07 00:00:00',
               'cd':0.0, 'cd_time':'2017-12-07 00:00:00',
}
def getEnvData():
    dataRtn = None
    try:
        db = pymysql.connect(MYSQL_HOST, MYSQL_ACCOUNT, MYSQL_PASSWORD, MYSQL_DATABASE, port=int(MYSQL_PORT))
    except Exception, err:
        print '>>>db_connect>>>', err
        return None
    try:
        cursor = db.cursor()
        for dbpt in DBParaTuple:
            sql = "SELECT val, instime FROM {tbl} ORDER BY id DESC LIMIT 1".format(tbl = dbpt[0])
            cursor.execute(sql)
            record = cursor.fetchone()
            if(record):
                EnvDataDict[dbpt[1]] = record[0]
                EnvDataDict[dbpt[2]] = str(record[1])
        dataRtn = json.dumps(EnvDataDict)
        # print dataRtn
    except Exception, err:
        print '>>>getEnvData>>>', err
        dataRtn = None
    finally:
        db.close()
        return dataRtn

class Handle(object):
    def GET(self, fn):
        # print '<Handle>get'
        if fn == "updateEnvData":
            return getEnvData()
        else:
            return getHtmlPage()

    def POST(self, fn):
        # print '<Handle>post'
        # postData = web.input()
        # cmd = postData['cmd']
        # print cmd
        return getHtmlPage()


